package com.lsl.filter;

import com.lsl.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().toString();
        
        // 排除不需要验证的接口
        if (path.startsWith("/vdm/api/account/login") || 
            path.startsWith("/vdm/api/account/signup") ||
            path.startsWith("/vdm/api/file/download")) {
            return chain.filter(exchange);
        }

        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            String responseBody = "{\"code\":401,\"message\":\"token无效，可能需要请重新登录\",\"data\":null}";
            try {
                return exchange.getResponse().writeWith(
                    Mono.just(exchange.getResponse().bufferFactory().wrap(responseBody.getBytes("UTF-8")))
                );
            } catch (java.io.UnsupportedEncodingException e) {
                return exchange.getResponse().writeWith(
                    Mono.just(exchange.getResponse().bufferFactory().wrap(responseBody.getBytes()))
                );
            }
        }

        token = token.substring(7);
        if (!JwtUtil.validateToken(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            exchange.getResponse().getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            String responseBody = "{\"code\":401,\"message\":\"token无效，可能需要请重新登录\",\"data\":null}";
            try {
                return exchange.getResponse().writeWith(
                    Mono.just(exchange.getResponse().bufferFactory().wrap(responseBody.getBytes("UTF-8")))
                );
            } catch (java.io.UnsupportedEncodingException e) {
                return exchange.getResponse().writeWith(
                    Mono.just(exchange.getResponse().bufferFactory().wrap(responseBody.getBytes()))
                );
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1; // 高优先级
    }
}
